#!/usr/bin/env bash
set -x

# kill -9
kill_handler() {
  echo "kill -9 handler"
  $CATALINA_HOME/bin/shutdown.sh
  wait ${!}
  exit 137; # 128 + 9 #SIGKILL
}

# kill -10
usr1_handler() {
  echo "kill -10 handler"
  $CATALINA_HOME/bin/shutdown.sh
  wait ${!}
  exit 138; # 128 + 10 -- SIGUSR1
}

# kill -15
term_handler() {
  $CATALINA_HOME/bin/shutdown.sh
  wait ${!}
  exit 143; # 128 + 15 -- SIGTERM
}
# setup handlers
# on callback, kill the last background process, which is `tail -f /dev/null` and execute the specified handler
trap 'kill ${!}; kill_handler' SIGKILL
trap 'kill ${!}; usr1_handler' SIGUSR1
trap 'kill ${!}; term_handler' SIGTERM

# run application
cd $CATALINA_HOME
bin/startup.sh

# wait forever
while true
do
  tail -f $CATALINA_HOME/logs/catalina.out & wait ${!}
done